<template>
  <div class="dish-add-edit">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑菜品' : '新增菜品' }}</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回</el-button>
      </div>
      
      <el-form :model="dishForm" :rules="rules" ref="dishForm" label-width="100px" v-loading="loading">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="dishForm.name" placeholder="请输入菜品名称"></el-input>
        </el-form-item>
        
        <el-form-item label="菜品分类" prop="categoryId">
          <el-select v-model="dishForm.categoryId" placeholder="请选择菜品分类" style="width: 100%">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="菜品价格" prop="price">
          <el-input-number v-model="dishForm.price" :precision="2" :step="0.1" :min="0" style="width: 100%"></el-input-number>
        </el-form-item>
        
        <el-form-item label="菜品图片" prop="image">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/common/upload"
            :show-file-list="false"
            :headers="uploadHeaders"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload">
            <img v-if="dishForm.image" :src="dishForm.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="菜品描述" prop="description">
          <el-input type="textarea" v-model="dishForm.description" :rows="3" placeholder="请输入菜品描述"></el-input>
        </el-form-item>
        
        <el-form-item label="售卖状态">
          <el-radio-group v-model="dishForm.status">
            <el-radio :label="1">起售</el-radio>
            <el-radio :label="0">停售</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="口味信息">
          <div class="flavor-list">
            <div class="flavor-add">
              <el-select v-model="selectedFlavorType" placeholder="请选择口味类别" style="width: 150px; margin-right: 10px">
                <el-option label="甜度" value="甜度"></el-option>
                <el-option label="温度" value="温度"></el-option>
                <el-option label="忌口" value="忌口"></el-option>
                <el-option label="辣度" value="辣度"></el-option>
              </el-select>
              <el-button type="primary" icon="el-icon-plus" @click="addFlavor">添加口味</el-button>
            </div>
            <div v-for="(flavor, index) in dishForm.flavors" :key="index" class="flavor-item">
              <span class="flavor-name" style="width: 150px; margin-right: 10px">{{ flavor.name }}</span>
              <div class="flavor-tags">
                <el-tag
                  v-for="option in getFlavorOptions(flavor.name)"
                  :key="option"
                  :type="isFlavorSelected(flavor, option) ? 'primary' : 'info'"
                  @click="toggleFlavorValue(flavor, option)"
                  style="margin-right: 10px; margin-bottom: 10px; cursor: pointer">
                  {{ option }}
                </el-tag>
              </div>
              <el-button type="danger" icon="el-icon-delete" circle @click="removeFlavor(index)"></el-button>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getCategoryList } from '@/api/category'
import { addDish, updateDish, getDishById } from '@/api/dish'

export default {
  name: 'DishAddEdit',
  data() {
    return {
      isEdit: false,
      dishId: null,
      loading: false,
      categoryOptions: [],
      selectedFlavorType: '',
      flavorOptions: {
        甜度: ['无糖', '少糖', '半糖', '多糖', '全糖'],
        温度: ['热饮', '常温', '去冰', '少冰', '多冰'],
        忌口: ['不要葱', '不要蒜', '不要香菜', '不要辣'],
        辣度: ['不辣', '微辣', '中辣', '重辣']
      },
      dishForm: {
        name: '',
        categoryId: '',
        price: 0,
        image: '',
        description: '',
        status: 1,
        flavors: []
      },
      rules: {
        name: [
          { required: true, message: '请输入菜品名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择菜品分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入菜品价格', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '请上传菜品图片', trigger: 'change' }
        ]
      }
    }
  },
   computed: {
    uploadHeaders() {
      return {
        token: localStorage.getItem('token') || ''
      }
    }
  },
  created() {
    // 获取路由参数，判断是新增还是编辑
    this.dishId = this.$route.params.id
    this.isEdit = !!this.dishId
    
    // 获取分类列表
    this.fetchCategoryOptions()
    
    // 如果是编辑，获取菜品详情
    if (this.isEdit) {
      this.fetchDishDetail()
    }
  },
  methods: {
    // 获取分类选项
    fetchCategoryOptions() {
      // 获取菜品分类（type=1）
      getCategoryList(1)
        .then(res => {
          if (res.code === 1) {
            this.categoryOptions = res.data || []
          } else {
            this.$message.error(res.msg || '获取分类列表失败')
          }
        })
        .catch(err => {
          console.error('获取分类列表失败', err)
          this.$message.error('获取分类列表失败')
        })
    },
    
    // 获取菜品详情
    fetchDishDetail() {
      this.loading = true
      getDishById(this.dishId)
        .then(res => {
          if (res.code === 1) {
            const dishData = res.data
            // 填充表单数据
            this.dishForm = {
              id: dishData.id,
              name: dishData.name,
              categoryId: dishData.categoryId,
              price: dishData.price,
              image: dishData.image,
              description: dishData.description || '',
              status: dishData.status,
              flavors: (dishData.flavors || []).map(f => ({
                name: f.name,
                value: Array.isArray(f.value) ? f.value : typeof f.value === 'string' ? f.value.split(',') : f.value ? [f.value] : []
              }))
            }
          } else {
            this.$message.error(res.msg || '获取菜品详情失败')
            this.goBack()
          }
        })
        .catch(err => {
          console.error('获取菜品详情失败', err)
          this.$message.error('获取菜品详情失败')
          this.goBack()
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 图片上传成功处理
    handleImageSuccess(res, file) { // file参数由el-upload组件提供，包含上传文件信息
      console.log('图片上传成功', res, file)
      if (res.code === 1) {
        this.dishForm.image = res.data
        // 可以使用file.name获取文件名等信息，但当前不需要
      } else {
        this.$message.error(res.msg || '上传图片失败')
      }
    },
    
    // 图片上传前的验证
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    },
    
    // 添加口味
    addFlavor() {
      if (!this.selectedFlavorType) {
        this.$message.warning('请先选择口味类别')
        return
      }
      // 检查是否已经添加过该口味类别
      const exists = this.dishForm.flavors.some(f => f.name === this.selectedFlavorType)
      if (exists) {
        this.$message.warning('该口味类别已添加')
        return
      }
      this.dishForm.flavors.push({
        name: this.selectedFlavorType,
        value: []
      })
      this.selectedFlavorType = ''
    },

    // 检查口味是否被选中
    isFlavorSelected(flavor, option) {
      return Array.isArray(flavor.value) && flavor.value.includes(option)
    },

    // 切换口味选中状态
    toggleFlavorValue(flavor, option) {
      if (!Array.isArray(flavor.value)) {
        flavor.value = []
      }
      const index = flavor.value.indexOf(option)
      if (index === -1) {
        flavor.value.push(option)
      } else {
        flavor.value.splice(index, 1)
      }
    },

    // 获取对应口味类别的选项
    getFlavorOptions(flavorName) {
      return this.flavorOptions[flavorName] || []
    },
    
    // 移除口味
    removeFlavor(index) {
      this.dishForm.flavors.splice(index, 1)
    },
    
    // 提交表单
    submitForm() {
      this.$refs.dishForm.validate(valid => {
        if (valid) {
          // 验证口味信息
          const invalidFlavor = this.dishForm.flavors.some(flavor => 
            !flavor.name || 
            !Array.isArray(flavor.value) || 
            flavor.value.length === 0
          )
          if (this.dishForm.flavors.length > 0 && invalidFlavor) {
            this.$message.warning('请至少选择一个口味选项')
            return
          }
          
          this.loading = true
          // 处理口味数据，将数组转为字符串
          const formData = JSON.parse(JSON.stringify(this.dishForm))
          if (formData.flavors && formData.flavors.length > 0) {
            formData.flavors = formData.flavors.map(flavor => ({
              ...flavor,
              value: Array.isArray(flavor.value) ? flavor.value.join(',') : flavor.value
            }))
          }
          
          // 根据isEdit判断是新增还是修改
          const request = this.isEdit ? updateDish(formData) : addDish(formData)
          
          request
            .then(res => {
              if (res.code === 1) {
                this.$message.success(this.isEdit ? '修改成功' : '新增成功')
                this.goBack()
              } else {
                this.$message.error(res.msg || (this.isEdit ? '修改失败' : '新增失败'))
              }
            })
            .catch(err => {
              console.error(this.isEdit ? '修改菜品失败' : '新增菜品失败', err)
              this.$message.error(this.isEdit ? '修改菜品失败' : '新增菜品失败')
            })
            .finally(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    
    // 返回列表页
    goBack() {
      this.$router.push('/dish')
    }
  }
}
</script>

<style scoped>
.dish-add-edit {
  padding: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.flavor-list {
  margin-bottom: 10px;
}
.flavor-add {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.flavor-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.flavor-name {
  display: inline-block;
  background-color: #f0f2f5;
  padding: 0 10px;
  height: 40px;
  line-height: 40px;
  border-radius: 4px;
  text-align: center;
}
.flavor-tags {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  min-width: 250px;
}
.flavor-tags .el-tag {
  margin-right: 10px;
  margin-bottom: 10px;
  transition: all 0.3s;
}
.flavor-tags .el-tag:hover {
  transform: scale(1.05);
}
</style>